package com.zy.utils;

import com.zy.base.domain.DbConfig;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBHelper {

    public Object executeSql(DbConfig dbConfig, String sql){

        List<Map<String,Object>> resultList=new ArrayList<Map<String,Object>>();

        try {
            Class.forName(dbConfig.getConnectDriver());

            Connection conn = DriverManager.getConnection(dbConfig.getConnectUrl(), dbConfig.getUserName(), dbConfig.getPassword());

            PreparedStatement preparedStatement = conn.prepareStatement(sql);

            ResultSet resultSet = preparedStatement.executeQuery();

            ResultSetMetaData metaData = resultSet.getMetaData();

            List<String> colNameList=new ArrayList<String>();
            int cols_len = metaData.getColumnCount(); // 获取总的列数
            for (int i = 0; i < cols_len; i++) {
                //String col_name = metaData.getColumnName(i + 1); // 获取第 i列的字段名称
                //String col_Tpye = metaData.getColumnTypeName(i+1);//类型
                colNameList.add(metaData.getColumnLabel(i+1));
            }

            while (resultSet.next()) {
                Map<String, Object> map=new HashMap<String, Object>();
                for(int i=0;i<cols_len;i++){
                    String key=colNameList.get(i);
                    Object value=resultSet.getObject(colNameList.get(i));
                    map.put(key, value);
                }
                resultList.add(map);
            }

            resultSet.close();
            preparedStatement.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            e.printStackTrace();
        }

        return resultList;
    }

}
